package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.vo.Node;
import com.cy.pj.sys.dao.SysMenuDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.entity.SysMenu;
import com.cy.pj.sys.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.List;

/**
 * @author LiuXu
 * @create 2020-07-16 19:34
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    /**
     * @return List<> list
     */
    @Override
    public List<SysMenu> findObjects() {
        System.out.println("SysMenuServiceImpl.findObjects()");
        List<SysMenu> list = sysMenuDao.findObjects();
        if (list == null || list.size() == 0) {
            throw new ServiceException("没有对应的菜单信息");
        }
        return list;
    }

    @Override
    public int deleteObject(Integer id) {
        //验证合法性
        if (id == null || id < 0) {
            throw new IllegalArgumentException("清先选择");
        }
        //基于id进行子元素查询
        int count = sysMenuDao.getChildCount(id);
        if (count > 0) {
            throw new ServiceException("清先删除子菜单");
        }

        //删除角色，菜单关系数据
        sysRoleMenuDao.deleteObjectsByMenuId(id);
        //删除菜单元素
        int rows = sysMenuDao.deleteObject(id);
        if (rows == 0) {
            throw new ServiceException("此菜单可能已不存在");
        }
        //返回结果
        return rows;
    }

    @Override
    public List<Node> findZtreeMenuNodes() {
        return sysMenuDao.findZtreeMenuNodes();
    }

    @Override
    public int saveObject(SysMenu entity) {
        //合法性验证
        if (entity == null) {
            throw new IllegalArgumentException("保存对象不能为空");
        }
        if (StringUtils.isEmpty(entity.getName())) {
            throw new IllegalArgumentException("菜单名不能为空");
        }
        //保存数据
        int rows = sysMenuDao.insertObject(entity);
        return rows;
    }

    @Override
    public int updateObject(SysMenu entity) {
        //验证合法性
        if (entity == null) {
            throw new ServiceException("保存对象不能为空");
        }
        if (StringUtils.isEmpty(entity.getName())) {
            throw new ServiceException("菜单名不能为空");
        }
        //更新数据
        int rows = sysMenuDao.updateObjext(entity);
        if (rows == 0) {
            throw new ServiceException("记录可能已不存在");
        }

        return rows;
    }
}
